<template>
  <el-drawer
    custom-class="drawer-box"
    :title="'通知公告管理'"
    :close-on-click-modal="false"
    size="80%"
    :before-close="_=>{this.visible=false}"
    :visible.sync="visible"
    :close-on-press-escape="false"
    :show-close="false"
    :wrapperClosable="false"
  >
    <el-container>
      <el-main>
        <el-row :gutter="20" style="margin: 0">
          <el-col :span="6" :offset="18" class="learn-drawer-range-box-buttons">
            <el-button
              class="el-icon-check"
              type="text"
              @click="onSubmit"
              :loading="loading"
              style="color: #67C23A;font-size:24px"
            />
            <el-button
              class="el-icon-close"
              type="text"
              @click="onClose"
              style="color: #F56C6C;font-size: 24px"
            />
          </el-col>
        </el-row>
        <el-form :model="dataForm" ref="dataForm" :rules="dataRule" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="标题" prop="title">
                <el-input v-model="dataForm.title" placeholder="这里是标题"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6" v-if="isParams">
              <el-form-item label="内容ID" prop="params">
                <el-input type="number" v-model="dataForm.params"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否发布" prop="isShow">
                <el-switch
                  v-model="dataForm.isShow"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                ></el-switch>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="文章/链接" prop="type">
                <el-radio-group v-model="dataForm.jumpType" @change="typeChange">
                  <el-radio style="margin: 0 6px 16px 0" :label="1" border>文字通知</el-radio>
                  <!--<el-radio :label="2">链接</el-radio>-->
<!--                  <el-radio style="margin: 0" :label="3" border>跳转链接</el-radio>-->
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item
                label-width="0"
                v-if="parseInt(dataForm.jumpType) === 1"
                prop="content"
                class="rich-editor-box"
              >
                <ck-editor ref="ckEditor" :change="contentChanged" />
              </el-form-item>
              <el-form-item
                label-width="0"
                v-else-if="parseInt(dataForm.jumpType) === 2"
                prop="content"
              >
                <el-input type="text" v-model="dataForm.content" placeholder="文章链接" />
              </el-form-item>
              <el-form-item label-width="0" v-else prop="moduleId">
                <el-select
                  style="width: 100%"
                  v-model="dataForm.moduleId"
                  @change="moduleChange"
                  filterable
                  clearable
                  placeholder="点击选择模块"
                >
                  <el-option
                    v-for="item in moduleList"
                    :key="item.index"
                    :label="item.moduleName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <exam-type
            ref="examType"
            :setUserList="setUserList"
            :form="dataForm"
            :examTypeChange="examTypeChange"
            :examUserArrClose="examUserArrClose"
            :setLoading="setLoading"
            :handleSelectionChange="handleSelectionChange"
          />
          <!--<el-form-item label="参与人员" prop="trainType">
                        <el-radio-group v-model="dataForm.correlationType" @change="typeChange">
                            <el-radio :label="0">全员参加</el-radio>
                            <el-radio :label="1">按人员参与</el-radio>
                        </el-radio-group>
                        <el-button
                                v-if="dataForm.correlationType == 1"
                                typeof="primary"
                                style="margin-left: 20px"
                                @click="handlerOpenUserDialog"
                        >选择参与人员
                        </el-button>
                        <el-form-item prop="userList" v-if="dataForm.correlationType == 1">
                            <el-table :data="dataForm.userList" max-height="300">
                                <el-table-column type="index" label="序号" width="80" align="center"/>
                                <el-table-column property="realname" label="姓名" width="200"/>
                                <el-table-column property="deptName" label="部门"/>
                                <el-table-column property="gender" label="性别">
                                    <template slot-scope="scope">
                                        <el-tag v-if="scope.row.gender==1">男</el-tag>
                                        <el-tag v-else>女</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column>
                                    <template slot-scope="scope">
                                        <el-button type="text"
                                                   @click="deleteHandle(scope.$index)">删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-form-item>
          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit()" :loading="loading">确定</el-button>
        </div>

        <!--<el-dialog title="人员列表" :visible.sync="dialogUserVisible" append-to-body>
                    <el-form :inline="true" :model="dataForm"
                             @keyup.enter.native="getUserList()">
                        <el-form-item>
                            <el-input v-model="dataForm.realname" placeholder="请输入姓名" clearable
                                      @clear="getUserList()"
                                      style="width: 160px;"/>
                            &lt;!&ndash;          <el-input v-model="dataForm.identityCard" placeholder="请输入身份证号" clearable @clear="getUserList()"  style="width: 160px;"></el-input>&ndash;&gt;
                            <el-input v-model="dataForm.mobile" placeholder="请输入手机号码" clearable
                                      @clear="getUserList()"
                                      style="width: 160px;"/>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="getUserList()">查询</el-button>
                        </el-form-item>
                    </el-form>
                    <el-table :data="userList" v-loading="dataListLoading" @selection-change="handleSelectionChange"
                              ref="multipleTable" max-height="500">
                        <el-table-column type="selection" width="30"/>
                        <el-table-column type="index" label="序号" width="80" align="center"/>
                        <el-table-column property="realname" label="姓名" width="200"/>
                        <el-table-column property="deptName" label="部门"/>
                        <el-table-column property="gender" label="性别">
                            <template slot-scope="scope">
                                <el-tag v-if="parseInt(scope.row.gender)===1">男</el-tag>
                                <el-tag v-else>女</el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                            @size-change="sizeChangeHandle"
                            @current-change="currentUserChangeHandle"
                            :current-page="pageIndex"
                            :page-sizes="[10, 20, 50]"
                            :page-size="pageSize"
                            :total="totalCount"
                            layout="total, sizes, prev, pager, next, jumper"
                            style="margin-top: 10px"
                    ></el-pagination>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogUserVisible = false">取 消</el-button>
                        <el-button type="primary" @click="selectUserSubmit" :loading="loading">确 定</el-button>
                    </div>
        </el-dialog>-->
      </el-main>
    </el-container>
  </el-drawer>
</template>

<script>
import Vue from 'vue'
import ExamType from '../../../components/examType/exam-type'
import CkEditor from '../../../components/ckEditor/ckEditor'

export default {
  name: 'notice-add',
  components: {
    CkEditor,
    ExamType
  },
  data() {
    return {
      setUserList: [],
      visible: false,
      loading: false,
      uploadImgUrl:
        this.$http.adornUrl('/file/upload?token=') + Vue.cookie.get('token'),
      moduleList: [],
      isParams: false,
      dialogUserVisible: false,
      dataListLoading: false,
      dataForm: {
        id: '',
        moduleId: '',
        title: '',
        content: '',
        jumpType: 1,
        examType: 0,
        isShow: true,
        sort: 0,
        userList: [],
        deptIds: [],
        params: ''
      },
      pageIndex: 1,
      pageSize: 50,
      totalCount: 0,
      selectUserList: [],
      multipleSelection: [],
      userList: [],
      deptIds: [],
      deptList: [],
      deptListTreeProps: {
        multiple: true,
        checkStrictly: true,
        expandTrigger: 'hover',
        label: 'name',
        value: 'id',
        children: 'children'
      },
      dataRule: {
        content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getmoduleList()
  },
  methods: {
    setLoading(val) {
      this.loading = val
    },
    examTypeChange(val) {
      this.dataForm.examType = val
      if (val) {
        this.initSearchForm({
          userIds: this.setUserList.map(x => x.userId).join(',')
        })
      }
    },
    examUserArrClose(item, index) {
      this.setUserList.splice(index, 1)
      this.searchFormInit()
    },
    onClose() {
      this.dataForm = {
        id: '',
        moduleId: '',
        title: '',
        content: '',
        jumpType: 1,
        examType: 0,
        isShow: true,
        sort: 0,
        userList: [],
        deptIds: [],
        params: ''
      }
      this.$refs.ckEditor && this.$refs.ckEditor.setData('')
      this.visible = false
    },
    contentChanged(content) {
      this.dataForm.content = content
    },
    searchFormInit() {
      this.$refs.examType.$refs.searchForm.search({
        userIds: this.setUserList.map(x => x.userId).join(',')
      })
    },
    initSearchForm(obj) {
      this.$refs.examType.$refs.searchForm.init(obj)
    },
    init(id) {
      this.dataForm.id = id
      this.visible = true
      // this.getDeptList()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/news-admin/notice/info/${this.dataForm.id}`
            ),
            method: 'post'
          }).then(data => {
            if (data && data.code === 200) {
              if (data.data.deptIdJson) {
                this.dataForm.deptIds = JSON.parse(data.data.deptIdJson)
              }
              this.setUserList = data.data.users || []
              this.dataForm.icon = data.data.icon
              this.dataForm.isShow = !!parseInt(data.data.isShow)
              this.dataForm.sort = data.data.sort
              this.dataForm.title = data.data.title
              this.dataForm.jumpType = data.data.jumpType
              this.dataForm.content = data.data.content
              this.$refs.ckEditor &&
                this.$refs.ckEditor.setData(data.data.content)
              this.dataForm.params = data.data.params
              this.dataForm.moduleId = data.data.moduleId
              this.dataForm.examType = data.data.correlationType > 0 ? 1 : 0
              if (Number(data.data.correlationType > 0)) {
                this.initSearchForm({
                  userIds: this.setUserList.map(x => x.userId).join(',')
                })
              }
            }
          })
        } else {
          this.setUserList = []
        }
      })
    },
    // 多选用户
    handleSelectionChange(val) {
      if (val.length) {
        this.setUserList = this.setUserList.concat(val)
        this.searchFormInit()
      }
    },
    // handleSelectionChange (val) {
    //   this.multipleSelection = val
    //   this.selectUserList[this.pageIndex - 1] = val
    // },
    // 用户列表翻页
    currentUserChangeHandle(val) {
      this.pageIndex = val
      this.getUserList()
    },
    // 打开用户列表弹窗
    handlerOpenUserDialog() {
      this.dialogUserVisible = true
      this.getUserList()
    },
    // 删除选中用户
    deleteHandle(index) {
      this.dataForm.userList.splice(index, 1)
    },

    // 获取部门列表
    /* getDeptList () {
        this.$http({
          url: this.$http.adornUrl('/usercenter-admin/dept/select'),
          method: 'post'
        }).then(data => {
          this.deptList = treeDataTranslate(data.data, 'id')
        })
      }, */
    // 获取用户列表
    getUserList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/usercenter-admin/user/list'),
        method: 'post',
        data: {
          realname: this.dataForm.realname,
          identityCard: this.dataForm.identityCard,
          mobile: this.dataForm.mobile,
          page:
            this.dataForm.realname ||
            this.dataForm.identityCard ||
            this.dataForm.mobile
              ? ''
              : this.pageIndex,
          limit: this.pageSize
        }
      }).then(res => {
        this.dataListLoading = false
        this.userList = res.data.list
        this.totalCount = res.data.totalCount
        // var list = []
        // for (let i = 0; i < this.userList.length; i++) {
        //   for (let j = 0; j < this.dataForm.userList.length; j++) {
        //     if (this.userList[i].userId === this.dataForm.userList[j].userId) {
        //       list.push(this.userList[i])
        //     }
        //   }
        // }
        // this.selectUserList[this.pageIndex - 1] = list

        // 用户选中状态回显
        let rows = this.selectUserList[this.pageIndex - 1]
        if (rows) {
          rows.forEach(row => {
            for (let i = 0; i < this.userList.length; i++) {
              if (parseInt(row.userId) === parseInt(this.userList[i].userId)) {
                this.$nextTick(_ =>
                  this.$refs.multipleTable.toggleRowSelection(
                    this.userList[i],
                    true
                  )
                )
              }
            }
          })
        }
      })
    },

    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getUserList()
    },
    // 获取模块列表
    getmoduleList() {
      this.$http({
        url: this.$http.adornUrl(`/sys/module/select`),
        method: 'post'
      }).then(res => {
        this.moduleList = res.data
      })
    },
    // 确认选中用户
    selectUserSubmit() {
      this.dataForm.userList = []
      this.selectUserList.forEach(item => {
        item.forEach(childItem => {
          this.dataForm.userList.push(childItem)
        })
      })
      this.dialogUserVisible = false
    },
    // 改变公告类型
    typeChange(e) {
      this.dataForm.userList = []
      this.dataForm.deptIds = []
      if (e === 3) {
        this.dataForm.content = ''
        this.$refs.ckEditor && this.$refs.ckEditor.setData('')
      }
    },
    // 改变跳转模块
    moduleChange(id) {
      for (let i = 0; i < this.moduleList.length; i++) {
        if (id === this.moduleList[i].id && this.moduleList[i].isParams === 1) {
          this.isParams = true
          return
        }
      }
      this.isParams = false
    },

    // 提交表单
    onSubmit() {
      var userIds = []
      if (this.dataForm.userList) {
        this.dataForm.userList.forEach(item => {
          userIds.push(item.userId)
        })
      }
      var deptIds = []
      if (this.dataForm.deptIds) {
        for (let i = 0; i < this.dataForm.deptIds.length; i++) {
          let idx = this.dataForm.deptIds[i].length - 1
          deptIds.push(this.dataForm.deptIds[i][idx])
        }
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.loading = true
          this.$http({
            url: this.$http.adornUrl(
              `/news-admin/notice/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: {
              id: this.dataForm.id,
              title: this.dataForm.title,
              isShow: this.dataForm.isShow ? 1 : 0,
              jumpType: this.dataForm.jumpType,
              content: this.dataForm.content,
              moduleId: this.dataForm.moduleId,
              sort: this.dataForm.sort,
              icon: this.dataForm.icon,
              correlationType: this.dataForm.examType,
              partakeIds:
                parseInt(this.dataForm.examType) > 0
                  ? this.setUserList.map(x => x.userId).join(',')
                  : [],
              deptIdJson: JSON.stringify(this.dataForm.deptIds),
              redirectUrl: this.dataForm.redirectUrl,
              params: this.dataForm.params
            }
          }).then(data => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500
              })
              this.visible = false
              this.$refs.ckEditor && this.$refs.ckEditor.setData('')
              this.$emit('refreshDataList')
            } else {
              this.$message.warning(data.msg)
            }
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.rich-editor-box {
  .w-e-text-container {
    height: 100px !important;
  }
}
</style>
